
import com.sun.jna.Native;
import com.sun.jna.Pointer;

import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import com.sun.jna.win32.StdCallLibrary;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;

public class javavideo {
    public static void main(String[] args) {
        getChildWindowName();
        startScreencapture();
    }

    static void getChildWindowName(){
        final User32 user32 = User32.INSTANCE;
        user32.EnumWindows(new WinUser.WNDENUMPROC() {

            int count = 0;
            @Override
            public boolean callback(WinDef.HWND hWnd, Pointer arg1) {
                byte[] windowText = new byte[512];
                User322.INSTANCE.GetWindowTextA(hWnd,windowText,512);
                String wText= null;
                try {
                    wText = new String(windowText,"gbk");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                if (wText.isEmpty()) {
                    return true;
                }
                if(!"".equals(wText)){
                    System.out.println("Found window with text " + hWnd + ", total " + ++count
                            + " Text: " + wText+"--"+wText.length());
                }
                return true;
            }
        }, null);

    }



    static void startScreencapture() {

        WinDef.RECT dimensionsOfWindow = new WinDef.RECT();


        //获取谷歌浏览器某一个标签的窗口
        WinDef.HWND parentWindow = User32.INSTANCE.FindWindow(null, "微信");
        User32.INSTANCE.GetWindowRect(parentWindow, dimensionsOfWindow );
        User32.INSTANCE.SetForegroundWindow(parentWindow);


        Robot robot = null;
        try {
            robot = new Robot();
        } catch (AWTException e) {
            e.printStackTrace();
        }

        System.out.println(dimensionsOfWindow.toRectangle());

        BufferedImage buf = robot.createScreenCapture(dimensionsOfWindow.toRectangle());
        File output = new File("C:\\Users\\Administrator\\Desktop\\workspace\\www.png");
        try {
            ImageIO.write(buf, "png", output);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

interface User322 extends StdCallLibrary {

    User322 INSTANCE = (User322) Native.loadLibrary("user32", User322.class);

    boolean EnumWindows(WinUser.WNDENUMPROC lpEnumFunc, Pointer arg);
    int GetWindowTextA(WinDef.HWND hWnd, byte[] lpString, int nMaxCount);

}

